<template>
  <div class="ace-container" :style="{ height: viewHeight + 'px' }">
    <!-- 官方文档中使用 id，这里禁止使用，在后期打包后容易出现问题，使用 ref 或者 DOM 就行 -->
    <!-- <img src="./icon/switch01.png" title="切换视图" @click="switchToView"> -->
    <div ref="ace" class="ace-code" />
  </div>
</template>
<script>
import ace from "ace-builds";
import "ace-builds/webpack-resolver";
import "ace-builds/src-noconflict/theme-monokai"; // 默认设置的主题
import "ace-builds/src-noconflict/mode-javascript"; // 默认设置的语言模式
import { Range, EditSession } from "ace-builds";
import "ace-builds/src-noconflict/ext-language_tools";

export default {
  name: "codeEditor",
  props: {
    objectJson: {
      type: String,
      default: "",
    },
    viewHeight: {
      type: String,
      default: "",
    },
    viewWidth: {
      type: String,
      default: "",
    },
  },
  data() {
    return {
      aceEditor: null,
      themePath: "ace/theme/github", // 不导入 webpack-resolver，该模块路径会报错ace/theme/github
      modePath: "ace/mode/html", // 同上
      color: "red",
    };
  },
  watch: {
    objectJson: {
      handler: function (newData, oldData) {
        console.info("newData");
      },
      immediate: true,
    },
  },
  mounted() {
    this.aceEditor = ace.edit(this.$refs.ace, {
      maxLines: 36, // 最大行数，超过会自动出现滚动条
      minLines: 36, // 最小行数，还未到最大行数时，编辑器会自动伸缩大小
      fontSize: 12, // 编辑器内字体大小
      theme: this.themePath, // 默认设置的主题
      // mode: this.modePath, // 默认设置的语言模式
      tabSize: 2, // 制表符设置为 4 个空格大小
      readOnly: false,
      highlightActiveLine: true,
      value: this.objectJson,
    });

    this.aceEditor.setShowPrintMargin(false); // 不显示垂直中线
    this.aceEditor.setAutoScrollEditorIntoView(true);
    this.aceEditor.setOptions({
      autoScrollEditorIntoView: true,
      maxLines: 36,
      enableBasicAutocompletion: true,
      enableSnippets: true,
      enableLiveAutocompletion: true,
      wrap: true,
    });
    // this.aceEditor.session.setMode("ace/mode/text");
    // registerSnippets(
    //   this.aceEditor.session,
    //   "javascript",
    //   createSnippets([
    //     { name: "build", code: 'console.log("build")' },
    //     { name: "destroy", code: 'console.log("destroy")' },
    //   ])
    // );
  },
  methods: {
    switchToView() {
      this.$emit("switchToView", false);
    },
    setValue(val) {
      this.aceEditor.setValue(val);
    },
    getValue(val) {
      return this.aceEditor.getValue(val);
    },
  },
};
</script>
<style lang="less" scoped>
.ace-container {
  position: relative;
  height: 500px;
  .ace-code {
    box-shadow: grey 1px 1px 2px;
    background-color: rgba(245, 245, 245, 245);
    z-index: 1;
  }
  img {
    position: fixed;
    width: 20px;
    height: 20px;
    float: right;
    z-index: 2;
    right: 5px;
    top: 155px;
  }
}
</style>
